package com.client;

import com.config.AppConfig;
import com.config.AppConstant;
import com.entity.UrlParams;
import com.utils.DadaSignatureUtil;
import com.utils.HttpClientUtil;
import com.utils.JSONUtil;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;
import java.util.*;

/**
 * @author zhang
 */
@Data
@Component
@NoArgsConstructor
public class DadaRequestClient {

    private UrlParams urlParams;

    private AppConfig appConfig;

    public DadaRequestClient(UrlParams urlParams, AppConfig appConfig) {
        this.urlParams = urlParams;
        this.appConfig = appConfig;
    }

    public DadaApiResponse callRpc() {
        String requestUrl = this.appConfig.getHost().concat(this.urlParams.getUrl());
        String requestParams = this.getRequestParams();

        try {
            String resp = HttpClientUtil.postRequest(requestUrl, requestParams);
            return JSONUtil.fromJson(resp, DadaApiResponse.class);
        }catch (Exception e){
            return DadaApiResponse.except();
        }
    }


    private String getRequestParams() {
        Map<String, String> requestParams = new HashMap<String, String>(8);
        requestParams.put("source_id", this.appConfig.getSourceId());
        requestParams.put("app_key", this.appConfig.getAppKey());
        requestParams.put("timestamp", String.valueOf(System.currentTimeMillis()));
        requestParams.put("format", AppConstant.FORMAT);
        requestParams.put("v", AppConstant.V);
        requestParams.put("body", this.urlParams.getParams());
        requestParams.put("signature", DadaSignatureUtil.getSign(requestParams,appConfig));
        return JSONUtil.toJson(requestParams);
    }


}
